package com.zgh.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zgh.domain.*;
import com.zgh.mapper.NewsMapper;
import com.zgh.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class NewsService {
    @Autowired
    private NewsMapper newsMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 查询所有新闻
     *
     * @return 新闻集合
     */
    public List<News> findAllNews(String provinceName) {
        QueryWrapper<News> newsQueryWrapper = new QueryWrapper<>();
        if ("全部".equals(provinceName)) {
            newsQueryWrapper.orderByDesc("releaseTime");
        } else {
            newsQueryWrapper.orderByDesc("releaseTime").eq("provinceName", provinceName);
        }
        return newsMapper.selectList(newsQueryWrapper);
    }

    /**
     * 根据id查询新闻
     *
     * @param id 新闻id
     * @return 新闻
     */
    public News findNewsById(String id) {
        QueryWrapper<News> newsQueryWrapper = new QueryWrapper<>();
        newsQueryWrapper.eq("id", id);
        return newsMapper.selectOne(newsQueryWrapper);
    }

    /**
     * 查询新闻（前三条）
     *
     * @return
     */
    public List<News> findNews(String provinceName) {
        QueryWrapper<News> newsQueryWrapper = new QueryWrapper<>();
        if ("全部".equals(provinceName)) {
            newsQueryWrapper.orderByDesc("releaseTime").last("limit 0,3");
        } else {
            newsQueryWrapper.eq("provinceName", provinceName).orderByDesc("releaseTime").last("limit 0,3");
        }
        return newsMapper.selectList(newsQueryWrapper);
    }

    /**
     * 上传新闻
     *
     * @param news1
     * @return 失败或成功
     */
    public int uploadNews(News news1) {
        Integer userId = news1.getUser().getId();
        LambdaUpdateWrapper<User> userLambdaUpdateWrapper = new UpdateWrapper<User>().lambda();
        userLambdaUpdateWrapper.eq(User::getId, userId);
        User user1 = userMapper.selectOne(userLambdaUpdateWrapper);
        news1.setUser(user1);
        int userid = user1.getId();
        news1.setUserId(userid);
        news1.setUser(user1);
        news1.setReleaseTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        int pd = newsMapper.insert(news1);
        if (pd == 1) {
            return 1;
        } else {
            return 0;
        }
    }


    /**
     * 分页查询获取所有新闻信息
     *
     * @return newsList
     */
    public ipageNews getAllNewsInfo(int page1, int PAGE_RECORDS_NUM, String query) {
        List<News> newsList = new ArrayList<News>();
        // 设置条件构造器
        QueryWrapper<News> wrapper = new QueryWrapper<>();
        wrapper.like("title", query);
        // 构造分页信息，其中的Page<>(page, PAGE_RECORDS_NUM)的第一个参数是页数，而第二个参数是每页的记录数
        IPage<News> newsPage = new Page<>(page1, PAGE_RECORDS_NUM);
        // page(postPage, wrapper)这里的第一个参数就是上面定义了的Page对象，第二个参数就是上面定义的条件构造器对象，通过调用这个方法就可以根据你的分页信息以及查询信息获取分页数据
        IPage<News> news1IPage = newsMapper.selectPage(newsPage, wrapper);
        // 封装数据，其中getRecords()是获取记录数，getCurrent()获取当前页数，getPages()获取总页数，getTotal()获取记录总数，还要其他更多的方法，大家可以自行查看，在这里就不过多赘述了
        newsList = news1IPage.getRecords();
        for (News news : newsList) {
            int userId = news.getUserId();
            User user = userMapper.selectById(userId);
            news.setUser(user);
        }
        Long total = news1IPage.getTotal();
        ipageNews ipageNews = new ipageNews();
        ipageNews.setNewsList(newsList);
        ipageNews.setTotal(total.intValue());
        return ipageNews;
    }

    /**
     * 通过id 获取新闻信息
     *
     * @param id
     * @return 新闻
     */
    public News getNewsById(Integer id) {
        News news = newsMapper.selectById(id);
        User user = userMapper.selectById(news.getUserId());
        news.setUser(user);
        return news;
    }

    /**
     * 保存新闻信息
     *
     * @param news1
     * @return
     */
    public int saveInfoByid(News news1) {
        QueryWrapper<News> wrapper = new QueryWrapper<>();
        wrapper.eq("id", news1.getId());
        News news = newsMapper.selectOne(wrapper);
        news.setTitle(news1.getTitle());
        UpdateWrapper newsUpdateWrapper = new UpdateWrapper();
        newsUpdateWrapper.eq("id", news1.getId());
        return newsMapper.update(news, newsUpdateWrapper);
    }

    // 删除新闻通过id
    public int deleteByid(Integer id) {
        int i = newsMapper.deleteById(id);
        return i;
    }


    /**
     * 通过点赞量和搜索词获取新闻
     *
     * @return 新闻列表
     */
    public List<News> getNewsByValue(String value) {
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        if (value != null) {
            queryWrapper.like("title", value);
        }

        List<News> newsList = newsMapper.selectList(queryWrapper);
        for (News news : newsList) {
            User user = userMapper.selectById(news.getUserId());
            news.setUser(user);
        }
        return newsList;
    }

    /**
     * 根据条件查询新闻
     * @param condition 条件
     * @return 集合
     */
    public List<News> findNewsByCondition(String condition,String region) {
        QueryWrapper<News> newsQueryWrapper = new QueryWrapper<>();

        newsQueryWrapper.eq("provinceName",region).like("title",condition)
                .or().like("content",condition)
                .or().like("provinceName",condition);
       return newsMapper.selectList(newsQueryWrapper);
    }
}
